package com.example.finalproject.adapter;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.example.finalproject.R;

import java.util.List;

public class WallpaperAdapter extends RecyclerView.Adapter<WallpaperAdapter.ViewHolder> {
    public static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView imageView;
        public ViewHolder(View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.wallpaperImageView);
        }
    }

    public interface OnWallpaperSelectedListener {
        void onWallpaperSelected(String wallpaperName);
    }

    private final Context context;
    private final List<String> wallpaperNames;
    private final OnWallpaperSelectedListener listener;

    public WallpaperAdapter(Context context, List<String> wallpaperNames,
                            OnWallpaperSelectedListener listener) {
        this.context = context;
        this.wallpaperNames = wallpaperNames;
        this.listener = listener;
    }

    public WallpaperAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.wallpaper_item_list, parent, false);
        return new ViewHolder(view);
    }

    public void onBindViewHolder(WallpaperAdapter.ViewHolder holder, int position) {
        String name = wallpaperNames.get(position);
        int resId = context.getResources().getIdentifier(name, "drawable", context.getPackageName());
        Drawable drawable = ContextCompat.getDrawable(context, resId);
        holder.imageView.setImageDrawable(drawable);

        holder.itemView.setOnClickListener(v -> {
            // 回调通知
            listener.onWallpaperSelected(name);
        });
    }

    public int getItemCount() {
        return wallpaperNames.size();
    }
}
